<template>
	<view class="container">
		<CustomNavbar :title="pageTitle" :style="navbarStyle" />
		<u-form :model="form" :rules="rules" ref="uForm" label-width="80">
			<!-- 头像 -->
			<u-form-item label="头像：" prop="avatar" borderBottom>
				<view class="cover-wrap">
					<image class="cover" v-if="form.avatar" @click="uploadAvatar" :src="form.avatar"></image>
					<image class="cover" v-else @click="uploadAvatar" src="../../static/images/m-cover.jpg"
						mode="scaleToFill"></image>
				</view>
			</u-form-item>
			<!-- 姓名 -->
			<u-form-item label="我的姓名：" prop="nickName" borderBottom>
				<u-input v-model="form.nickName" placeholder="请输入昵称" clearable />
			</u-form-item>
			<!-- 性别 -->
			<u-form-item label="性别：" prop="sex" borderBottom @click="showGender = true">
				<u-input v-model="form.sex" disabled placeholder="请选择性别" suffixIcon="arrow-down" />
				<u-picker :show="showGender" :columns="genderColumns" keyName="label" @confirm="genderConfirm"
					@cancel="showGender = false" />
			</u-form-item>
			<!-- 手机号 -->
			<u-form-item label="手机号：" prop="phonenumber" borderBottom>
				<u-input v-model="form.phonenumber" type="number" maxlength="11" placeholder="请输入手机号" clearable />
			</u-form-item>
			<!-- 地区选择 -->
			<u-form-item label="所在地区：" prop="regionText" borderBottom @click="showRegion = true">
				<u-input v-model="form.regionText" disabled placeholder="请选择省市区" suffixIcon="arrow-down" />
				<u-picker :show="showRegion" :loading="loading" ref="uPicker3" :columns="columns3"
					@confirm="regionConfirm" @cancel="showRegion = false" @change="changeHandler"></u-picker>
			</u-form-item>
			<!-- 行业选择 -->
			<u-form-item label="所属行业：" prop="industry" borderBottom @click="showIndustry = true">
				<u-input v-model="form.industry" disabled placeholder="请选择行业" suffixIcon="arrow-down" />
				<u-picker :show="showIndustry" :columns="industryColumns" keyName="label" @confirm="industryConfirm"
					@cancel="showIndustry = false" />
			</u-form-item>
			<!-- 个人简介 -->
			<u-form-item label="个人简介：" prop="briefInfo" borderBottom>
				<u-textarea v-model="form.briefInfo" placeholder="请填写个人简介" maxlength="200" />
			</u-form-item>
		</u-form>
		<uni-popup ref="qrPopup" type="center" :mask-click="true">
			<view class="qr-popup" @touchmove.stop.prevent>
				<image v-if="form.industry == '废纸'" show-menu-by-longpress="true"
					src="https://market-fenjie-1331975401.cos.ap-nanjing.myqcloud.com/2025/03/31/19af1f6ecc8f4a8a9cb6dbb5114973d4.jpg"
					mode="widthFix" class="qrcode-img"></image>
				<image v-else show-menu-by-longpress="true"
					src="https://market-fenjie-1331975401.cos.ap-nanjing.myqcloud.com/2025/03/31/568ecdcc7030482a809f1e4d0a7fe32c.jpg"
					mode="widthFix" class="qrcode-img"></image>
				<view class="btn-group">
					<!-- <u-button type="primary" text="保存图片" custom-style="margin-right:20rpx;flex:1" @click="saveQrcode" /> -->
					<u-button type="success" text="跳转首页" custom-style="margin-left:20rpx;flex:1" @click="goHome" />
				</view>
			</view>
		</uni-popup>
		<!-- 提交按钮 -->
		<view class="submit-btn">
			<u-button type="primary" text="保存信息" :loading="loading" @click="submitForm" />
		</view>
	</view>
</template>
<script>
	import CustomNavbar from '@/components/CustomNavbar.vue';
	const api = require('../../util/api.js');
	export default {
		components: {
			CustomNavbar
		},
		data() {
			return {
				isSaved: false, // 标记是否已保存
				cover: '',
				pageTitle: '完善信息',
				navbarStyle: {},
				loading: false,
				columns3: [],
				columnData: [],
				lat: '',
				lon: '',
				form: {
					avatar: '',
					province: '江苏省', // 省
					city: '徐州市', // 市
					district: '睢宁县', // 区
					nickName: '',
					sex: '',
					regionText: '',
					phonenumber: '',
					industry: '',
					briefInfo: '',
					lat: '116.5',
					lon: '34.4'
				},
				regionText: '', // 组合后的地区文本
				// 选择器控制
				showGender: false,
				showRegion: false,
				showIndustry: false,
				// 性别选项
				genderColumns: [
					[{
						label: '男',
						value: 1
					}, {
						label: '女',
						value: 2
					}]
				],
				// 地区选项（示例数据）
				// 地区数据结构（示例）
				regionColumns: [
					[
						// 省
						{
							label: '广东省',
							value: 44
						}, {
							label: '浙江省',
							value: 33
						}
					],
					[
						// 市
						{
							label: '广州市',
							value: 4401
						}, {
							label: '深圳市',
							value: 4403
						}
					],
					[
						// 区
						{
							label: '天河区',
							value: 440106
						}, {
							label: '南山区',
							value: 440305
						}
					]
				],
				// 行业选项
				industryColumns: [
					[{
						label: '废纸',
						value: 1
					}, {
						label: '废塑',
						value: 2
					}, {
						label: '设备商',
						value: 4
					}]
				],
				// 验证规则
				rules: {
					// 添加头像验证规则
					avatar: [{
						required: true,
						message: '请上传头像',
						trigger: 'blur' // 需要自定义验证触发
					}],
					nickName: [{
						required: true,
						message: '姓名不能为空'
					}, {
						min: 2,
						max: 10,
						message: '姓名长度为2-10个字符'
					}],
					sex: [{
						required: true,
						message: '请选择性别'
					}],
					phonenumber: [{
						required: true,
						message: '手机号不能为空'
					}, {
						validator: (rule, value) => /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value),
						message: '手机号格式不正确',
						trigger: ['blur', 'change']
					}],
					regionText: [{
						required: true,
						message: '请选择所在地区'
					}],
					industry: [{
						required: true,
						message: '请选择所属行业'
					}]
				}
			};
		},
		onLoad() {
			// this.getMyLoction();
			this.getInfo();
		},
		// 在页面中新增生命周期函数
		onBackPress(options) {
			if (!this.isSaved) {
				uni.showModal({
					title: '未保存更改',
					content: '您有未保存的修改，确认要离开吗？',
					success: (res) => {
						if (res.confirm) {
							// 用户确认离开，允许退出
							this.isSaved = true; // 强制标记为已保存（避免循环提示）
							uni.navigateBack(); // 手动触发返回
						}
					}
				});
				return true; // 阻止默认返回行为
			}
		},
		methods: {
			getMyLoction() {
				// uni.showLoading({
				// 	title: '定位中,请稍后'
				// });
				const _that = this;
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						_that.lat = res.latitude;
						_that.lon = res.longitude;
						_that.form.lat = res.latitude;
						_that.form.lon = res.longitude;
						_that.getAddressByLanLen(res.latitude, res.longitude);
					}
				});
			},
			getAddressByLanLen(lat, lon) {
				let data = {
					lat: lat,
					lon: lon
				};
				this.$https.post(this.$api.getAddressByLanLen, data).then((res) => {
					if (res.code === 200) {
						const data = res.data;
						this.form.regionText = data.provinceName + data.cityName + data.districtName;
						this.form.province = data.provinceName;
						this.form.city = data.cityName;
						this.form.district = data.districtName;
						uni.setStorageSync('address', JSON.stringify(res.data));
						console.log(result); // 输出：指定字符后面的内容
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
					uni.hideLoading();
				});
			},
			getInfo() {
				this.$https.post(this.$api.getAddress).then((res) => {
					if (res.code === 200) {
						const data = res.data;
						this.columns3 = res.data.parent;
						this.columnData = res.data.child;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						this.show = false;
					}
				});
			},
			// 性别选择
			genderConfirm(e) {
				this.form.sex = e.value[0].label;
				this.showGender = false;
			},
			// 确认选择
			regionConfirm(e) {
				const p = e.value[0];
				const c = e.value[1];
				if ('全部' == p) {
					this.form.province = '';
					this.form.city = '';
				} else {
					this.form.province = p;
					this.form.city = c;
				}
				this.form.regionText = this.form.province + this.form.city;
				this.showRegion = false;
			},
			changeHandler(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker3
				} = e;
				const name = e.value[0];
				if (columnIndex === 0) {
					this.loading = true;
					// 模拟网络请求
					uni.$u.sleep(500).then(() => {
						picker.setColumnValues(1, this.columnData[index]);
						this.loading = false;
					});
				}
			},
			// 行业选择
			industryConfirm(e) {
				this.form.industry = e.value[0].label;
				this.showIndustry = false;
			},
			// 修正方法名并实现上传逻辑
			async uploadAvatar() {
				const _that = this;
				try {
					// 选择图片
					uni.chooseImage({
						sourceType: ['camera', 'album'],
						success: function(res) {
							const url = res.tempFilePaths[0];
							uni.uploadFile({
								url: _that.$api.upload,
								filePath: url,
								name: 'file',
								header: {
									'Content-Type': 'application/json',
									Authorization: 'Bearer ' + uni.getStorageSync('token')
								},
								formData: {},
								success: (uploadFileRes) => {
									const result = uploadFileRes.data;
									var res = JSON.parse(result);
									if (res.code === 200) {
										_that.form.avatar = res.data.url;
										_that.$refs.uForm.validateField('avatar'); // 触发验证
									} else {
										uni.showToast({
											title: res.errMsg,
											icon: 'none'
										});
									}
								}
							});
						}
					});
				} catch (error) {
					console.error('上传失败:', error);
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			// 表单提交
			async submitForm() {
				console.log(this.form);
				try {
					this.loading = true;
					// 验证表单
					await this.$refs.uForm.validate();
					// 模拟API请求
					this.$https.post(this.$api.updateProfile, this.form).then((res) => {
						if (res.code === 200) {
							this.isSaved = true; // 标记为已保存
							this.$refs.qrPopup.open(); // 打开二维码弹窗
						} else {
							uni.showToast({
								title: '修改失败',
								icon: 'error'
							});
						}
					});
					// uni.$u.toast('保存成功')
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/home/index'
						});
					}, 1500);
				} catch (error) {
					console.error('表单验证失败:', error);
				} finally {
					this.loading = false;
				}
			},
			// 保存图片到相册
			async saveQrcode() {
				try {
					const tempFilePath = await new Promise((resolve, reject) => {
						uni.downloadFile({
							url: 'https://market-fenjie-1331975401.cos.ap-nanjing.myqcloud.com/2025/02/22/8601d7c68ec24f25ab248d5adf4e39b3.png',
							success: (res) => resolve(res.tempFilePath),
							fail: reject
						});
					});
					await uni.saveImageToPhotosAlbum({
						filePath: tempFilePath
					});
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
					// this.$refs.qrPopup.close();
				} catch (err) {
					this.handleSaveError(err);
				}
			},
			// 处理保存失败
			handleSaveError(err) {
				if (err.errMsg.includes('auth')) {
					uni.showModal({
						title: '权限提醒',
						content: '需要相册权限才能保存',
						success: (res) => {
							if (res.confirm) uni.openSetting();
						}
					});
				} else {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			},
			// 跳转首页
			goHome() {
				uni.switchTab({
					url: '/pages/login/index'
				});
				this.$refs.qrPopup.close();
			}
		}
	};
</script>
<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		padding-top: 200rpx;

		/deep/ .u-input {
			background-color: #fff !important;
		}

		/deep/ .navbar {
			display: flex;
			justify-content: center;
		}

		.cover-wrap {
			display: flex;

			.cover {
				border: 1rpx solid #55aaff;
				width: 108rpx;
				height: 108rpx;
				border-radius: 55rpx;
			}
		}

		.submit-btn {
			margin: 80rpx 30rpx 0;

			/deep/ .u-button {
				height: 90rpx;
				border-radius: 45rpx;
				font-size: 32rpx;
			}
		}

		/deep/ .u-form-item {
			padding: 8rpx 0;

			.u-form-item__body {
				align-items: center;
			}
		}

		/deep/ .u-textarea {
			padding: 8rpx;
			background-color: #fff;
			border-radius: 12rpx;
		}

		.qr-popup {
			background: #fff;
			border-radius: 20rpx;
			padding: 40rpx;
			width: 600rpx;

			.qrcode-img {
				width: 400rpx;
				display: block;
				margin: 0 auto;
			}

			.btn-group {
				margin-top: 40rpx;
				display: flex;
				justify-content: space-between;
			}
		}

		// 阻止弹窗背景滚动
		/deep/ .uni-popup__wrapper {
			overflow: hidden !important;
		}
	}
</style>